<?php

namespace App\Console\Commands\ChatGroup;


use App\Enums\Common\NsqEnum;
use App\Service\ChatGroup\ChatGroupMessageReadService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;
use Illuminate\Support\Facades\Validator;

class NsqSubMqttSubscribe extends Command
{
    protected $signature = 'nsq:sub-mqtt-subscribe';

    protected $description = 'nsq订阅 - mqtt订阅';

    public function handle()
    {
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_MQTT_SUBSCRIBE, NsqEnum::CHANNEL_TIGER_MQTT_SUBSCRIBE,
                function (Message $message) {

                    Log::info('sub-mqtt-subscribe:', $message->data());

                    // debug
                    if (isTest()) {
                        dump($message->data());
                    }

                    $data = $message->data();

                    // 参数校验
                    if (!$this->valid($data)) {
                        $message->done();
                        return;
                    }

                    try {
                        $this->doHandle($data);

                    } catch (\Exception $e) {
                        Log::warning($e);
                    }

                    $message->done();
                });
    }

    private function valid(array $data): bool
    {
        $validator = Validator::make($data, [
            'topic' => 'required|string',
            'msg'   => 'required|array'
        ]);

        if ($validator->fails()) {
            Log::warning("NsqSubMqttSubscribe valid error:" . $validator->errors()->first(), $data);
            return false;
        }

        return true;
    }

    /**
     * 注意这里的通配符用*
     * @var array|string[]
     */
    private array $pattern = [
        'chatGroup/receiveMsg/*',
    ];

    /**
     * 通配符匹配topic
     * @param string $topic
     * @return string
     */
    private function patternTopic(string $topic): string
    {
        foreach ($this->pattern as $pattern) {
            if (fnmatch($pattern, $topic)) {
                return $pattern;
            }
        }

        return '';
    }

    private function doHandle(array $data)
    {
        $topic = $data['topic'];
        $msg   = $data['msg'];

        // 匹配topic
        // chatGroup/receiveMsg/*
        $patternTopic = $this->patternTopic($topic);
        if (!$patternTopic) {
            Log::warning("NsqSubMqttSubscribe not pattern topic: {$topic}");
            return;
        }

        // 暂时没其他业务，先简单写写
        switch($patternTopic) {
            case 'chatGroup/receiveMsg/*':

                // 清空未读消息
                $userId = $msg['userId'] ?? 0;
                $groupId = $msg['groupId'] ?? 0;

                if (!$userId || !$groupId) {
                    return;
                }

                (new ChatGroupMessageReadService($userId))->readMessage($groupId);

                break;
        }
    }
}
